package com.lyEducation.security.config;

import com.alibaba.fastjson.JSON;
import com.lyEducation.controllers.dto.system.userDetails.UserDetailsImpl;
import com.lyEducation.core.base.SysConstants;
import com.lyEducation.core.system.SysUserService;
import com.lyEducation.entities.system.SysUserEntity;
import com.lyEducation.repository.system.SysUserRepository;
import com.lyEducation.security.SecurityConfig;
import com.lyEducation.util.jwt.JwtUtil;
import com.lyEducation.util.jwt.JwttokenconfigEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component("authenticationSuccessHandlerImpl")
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private JwtUtil jwtUtil;

  @Override
  public void onAuthenticationSuccess(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      Authentication authentication)
      throws IOException, ServletException {
    Map<String, Object> paramMap = new HashMap<String, Object>();
    UserDetailsImpl userDetails=null;
    SysUserEntity sysUserEntity = null;
    try {
        sysUserEntity = (SysUserEntity) SecurityPrincipalContext.getUserDetails();
        sysUserEntity = sysUserRepository.setLoginUserRoleMenu(sysUserEntity);
      userDetails=sysUserEntity.createUserDetailsImpl();
      SecurityConfig.setAuthenticationToSecurityContext(userDetails, httpServletRequest);
    } catch (Exception e) {
      userDetails = SecurityPrincipalContext.getUserDetailsImpl();
    }

    sysUserService.updUserParamByLoginSuccess(httpServletRequest);
    httpServletResponse.setContentType("application/json;charset=utf-8");
    paramMap.put(JwttokenconfigEnum.jti.getValue(), userDetails.getId());
    paramMap.put(JwttokenconfigEnum.sub.getValue(), userDetails.getUsername());
    paramMap.put(SysConstants.PASSWORD.getValue(), userDetails.getPassword());
    paramMap.put(JwttokenconfigEnum.roles.getValue(), userDetails.getAuthorities());
    String jwtToken = jwtUtil.generateToken(paramMap);
    jwtUtil.addJwtTokenToRedisHash(userDetails.getId(), jwtToken);

    StringBuffer sb = new StringBuffer(jwtUtil.getJwttokenconfigBean().getTokenHead());
    sb.append(jwtToken);
    String jwtHeader = sb.toString();
    httpServletResponse.setHeader(jwtUtil.getJwttokenconfigBean().getHeader(), jwtHeader);
    PrintWriter out = httpServletResponse.getWriter();
//    ObjectMapper objectMapper = new ObjectMapper();
    paramMap.clear();
    paramMap.put("status","200");
    if(sysUserEntity!=null){
      paramMap.put("user",sysUserEntity.createSysUserDto());
//      sb.append(  "{\"status\":\"success\",\"msg\":" + objectMapper.writeValueAsString(sysUserEntity.createSysUserDto()) + "}");
    }
    out.write(JSON.toJSONString(paramMap));
    out.flush();
    out.close();
  }
}
